package cn.itcast.bos.service.base.impl;

import cn.itcast.bos.dao.base.CourierRepository;
import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.service.base.CourierService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;
import java.util.Set;


@Service
@Transactional
public class CourierServiceImpl implements CourierService {

    @Autowired
    private CourierRepository courierRepository;

    /**
     * //保存快递员
     * @param courier
     */
    @Override
    @RequiresPermissions("courier:add")
    public void save(Courier courier) {
        courierRepository.save(courier);
    }

    @Override//分多条件查询快递员
    public Page<Courier> findPageData(Specification<Courier> specification, Pageable pageable) {
        return courierRepository.findAll(specification,pageable);
    }

    @Override
    //批量删除快递员,逻辑上的删除
    public void delBatch(String[] idArray) {
        for (String idStr : idArray) {
            Integer id = Integer.parseInt(idStr);
            courierRepository.updateDelTag(id);
        }
    }

    @Override
    //批量恢复快递员,
    public void restoreBatch(String[] idArray) {
        for (int i = 0; i < idArray.length; i++) {
            String idStr = idArray[i];
            Integer id = Integer.parseInt(idStr);
            courierRepository.restoreBatch(id);
        }
    }

    @Override

    public List<Courier> findNoassociation() {
        Specification<Courier> specification = new Specification<Courier>() {
            @Override
            public Predicate toPredicate(Root<Courier> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                //查询条件,列表为空,表示
                Predicate p1 = cb.isEmpty(root.get("fixedAreas").as(Set.class));
                return p1;
            }

        };


        return courierRepository.findAll(specification);
    }


}
